/**
 * str new Date兼容性处理
 * 目前主要被 timeFormatter调用
 */
export function newDate(str) {
  let dpart;
  let tpart;
  if (/^\d+-\d{2}-\d{2}$/.test(str)) {
    dpart = (str.split(' ')[0]).split('-');
    return new Date(+dpart[0], +(dpart[1]) - 1, +dpart[2]);
  } else if (/^\d+-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(str)) {
    dpart = (str.split(' ')[0]).split('-');
    tpart = (str.split(' ')[1]).split(':');
    return new Date(+dpart[0], +(dpart[1]) - 1, +dpart[2], +tpart[0], +tpart[1], +tpart[2]);
  } else {
    return new Date(str);
  }
}

/**
 * element-ui时间选择器时间格式化， 时间戳的格式化
 * @param  time 时间戳
 * @param  {Number} type 格式化类型
 * @return {String}
 */
export function timeFormatter(time, type) {
  if (!time) {
    return '';
  }
  let zerofill = val => val >= 10 ? val : '0' + val
  let date = newDate(time);
  let year = date.getFullYear();
  let month = zerofill(date.getMonth() + 1);
  let day = zerofill(date.getDate());
  let hours = zerofill(date.getHours());
  let minutes = zerofill(date.getMinutes());
  let second = zerofill(date.getSeconds());
  let result = '';
  switch (type) {
  case 0: // 01-05
    result = `${month}-${day}`;
    break;
  case 1: // 11:12
    result = `${hours}-${minutes}`;
    break;
  case 2: // 2015-01-05
    result = `${year}-${month}-${day}`;
    break;
  case 3: // 2015年5月
    result = `${year}年${month}月`
    break;
  case 4: // 2015-01-05 11:12
    result = `${year}-${month}-${day} ${hours}:${minutes}`
    break;
  case 5: // 2015-01-05 00:00:00
    result = `${year}-${month}-${day} 00:00:00`;
    break;
  case 6: // 2015-01-05 23:59:59
    result = `${year}-${month}-${day} 23:59:59`;
    break;
  case 7: // 2015/01/05
    result = `${year}/${month}/${day}`;
    break;
  case 8: // 12:10
    result = `${hours}:${minutes}:${second}`;
    break;
  case 9: // 12:10:11
    result = `${hours}:${minutes}`;
    break;
  case 10: //2015
    result = `${year}`;
    break;
  case 11: //201511
    result = `${year}${month}`;
    break;
  case 12: //12/12
    result = `${month}/${day}`;
    break;
  default: // 2015-01-05 11:12:13
    result = `${year}-${month}-${day} ${hours}:${minutes}:${second}`;
    break;
  }
  return result;
}







/**
 * [wxbFromString 针对IOS进行的时间字符串转换函数]
 * @param  {[type]} str [description]
 * @return {[type]}     [description]
 */
export function wxbFromString(str) {
  var dpart, tpart;
  if (/^\d+-\d{2}-\d{2}$/.test(str)) {
    dpart = (str.split(' ')[0]).split('-');
    return new Date(+dpart[0], +(dpart[1]) - 1, +dpart[2]);
  } else if (/^\d+-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(str)) {
    dpart = (str.split(' ')[0]).split('-');
    tpart = (str.split(' ')[1]).split(':');
    return new Date(+dpart[0], +(dpart[1]) - 1, +dpart[2], +tpart[0], +tpart[1], +tpart[2]);
  } else {
    if (typeof str === 'number') {
      return new Date(str);
    } else {
      console.log('invalid format');
    }
  }
}
/**
 * 日期对象的格式化;
 * date Date Object or timeStamp
 * eg1: formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss')
 * eg2: formatDate(new Date().getTime(), 'yyyy-MM-dd hh:mm:ss')
 */
export function formatDate(date, fmt) {
  var obj = new Date();
  if (typeof date === 'number') {
    obj = new Date(date);
  } else if (typeof date === 'string') {
    date = Number(date);
    obj = new Date(date);
  } else if (typeof date === 'object') {
    obj = date;
  }
  var o = {
    "M+": obj.getMonth() + 1,
    "d+": obj.getDate(),
    "h+": obj.getHours(),
    "m+": obj.getMinutes(),
    "s+": obj.getSeconds(),
    "q+": Math.floor((obj.getMonth() + 3) / 3),
    "S": obj.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (obj.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    }
  }
  return fmt;
}
/*格式化时间戳*/
export function formatTime(addTime) {
  var weekDay = '';
  var today = new Date();
  today.setHours(0);
  today.setMinutes(0);
  today.setSeconds(0);
  var yesterday = new Date(new Date().setDate(today.getDate() - 1));
  yesterday.setHours(0);
  yesterday.setMinutes(0);
  yesterday.setSeconds(0);
  if (addTime.time > yesterday.getTime()) {
    if (addTime.time < today.getTime()) {
      weekDay = '昨天';
    } else {
      weekDay = formatDate(new Date(addTime.time), 'hh:mm');
    }
  } else {
    weekDay = formatDate(new Date(addTime.time), 'MM/dd');
  }
  return weekDay;
}
/**
 * 格式化手机号
 * @param telNo 手机号
 */
export function formatTelNum(telNo) {
  var inputPhone = '';
  if (typeof telNo == 'number') {
    telNo = telNo.toString();
  }
  if (typeof telNo == 'string') {
    inputPhone = telNo.replace(/\s+/g, '');
    var len = inputPhone.length;
    if (len >= 4 && len < 8) {
      inputPhone = inputPhone.substr(0, 3) + " " + inputPhone.substr(3);
    } else if (len >= 8 && len < 12) {
      inputPhone = inputPhone.substr(0, 3) + " " + inputPhone.substr(3, 4) + " " + inputPhone.substr(7);
    }
  } else {
    inputPhone = telNo;
    console.log('手机号格式化参数类型不正确');
  }
  return inputPhone;
}
/*
 * 格式化金额 32,122.55
 * @param money, 需要被格式化的金额
 * @param n, 小数点位数
 */
export function formatMoney(money, n) {
  n = n > 0 && n <= 20 ? n : 2;
  money = parseFloat((money + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
  var l = money.split(".")[0].split("").reverse(),
      r = money.split(".")[1];
  var t = "";
  for (var i = 0; i < l.length; i++) {
    t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
  }
  //return r != 0 ? t.split("").reverse().join("") + "." + r : t.split("").reverse().join(""); //即使是0也保留小数
  return t.split("").reverse().join("") + "." + r;
}
/**
 * 银行卡号分割
 * @param str
 **/
export function formatBankNo(str) {
  if (!str) {
    return str;
  }
  //四个字符加一个空格
  str = str.replace(/\s/g, '').replace(/(\d{4})(?=\d)/g, "$1 ");
  //优化语句：如果当前位置是空格字符，则自动清除掉
  if (str.charAt(str.length - 1) == ' ') {
    str = str.substring(0, str.length - 1);
  }
  return str;
}
/**
 * 去空格
 * @param str
 **/
export function trimAll(str) {
  if (!str) {
    return str;
  }
  str = str.toString(); //确保字符串
  return str.replace(/\s+/g, '');
}
/***
 * 字符串转驼峰
 * @param string 如demo-demo
 * @returns {string|void|XML|*} demoDemo
 */
export function stringToCamelCase(string) {
  return string.toLowerCase().replace(/-(.)/g, function(match, group1) {
    return group1.toUpperCase();
  });
}
/***
 * 驼峰转字符串
 * @param string 如demoDemo
 * @returns {string|void|XML|*} demo-demo
 */
export function camelCaseToString(string) {
  return string.replace(/([A-Z])/g, "-$1").toLowerCase();
}
/**
 * 反解析，将JSON转成String
 * @param qObj
 * @return {string}
 */
export function parseJsonToString(qObj) {
  var qArr = [];
  if (qObj) {
    for (var i in qObj) {
      qArr.push(i + '=' + qObj[i]);
    }
  }
  return qArr.join('&');
}
/**
 * [moneyCuter 将数字类型转化为每3个数字一个逗号的货币格式]
 * @param  {[string]}   [待转换的浮点数字串]
 * @return {[string]}   [转换后的标准货币格式字符串]
 */
export function moneyCuter(s) {
  if (/[^0-9\.]/.test(s)) {
    return "0.00";
  }
  if (s == null || s == "") {
    return "0.00";
  }
  s = s.toString().replace(/^(\d*)$/, "$1.");
  s = (s + "00").replace(/(\d*\.\d\d)\d*/, "$1");
  s = s.replace(".", ",");
  var re = /(\d)(\d{3},)/;
  while (re.test(s)) {
    s = s.replace(re, "$1,$2");
  }
  s = s.replace(/,(\d\d)$/, ".$1");
  return s;
}
/*将数字不进行四舍五入地转化为小数点后几位的格式,如果当前精确位数小于目标位数则往后面加0
 * 目标位数默认为2，如果传入非数字则返回0.00
 * @param {number or string} num 需要转化的数字
 * @param {array} digits 需要截取的位数
 * */
export function cutNumberByDigits(num, digits) {
  if (digits === void 0) {
    digits = 2;
  }
  var numberNum = Number(num);
  var numberDigits = Number(digits);
  if (isNaN(numberNum)) {
    return '0.00';
  }
  if (isNaN(numberDigits)) {
    numberDigits = 2;
  }
  return numberNum.toFixed(numberDigits + 1).slice(0, -1);
}

/**
 *
 * @param {*} day  7 7天后  -7 7天前
 */
export function getDay(day,type) {
  //Date()返回当日的日期和时间。
  var days = new Date();
  //getTime()返回 1970 年 1 月 1 日至今的毫秒数。
  var gettimes = days.getTime() + 1000 * 60 * 60 * 24 * day;
  //setTime()以毫秒设置 Date 对象。
  days.setTime(gettimes);
  var year = days.getFullYear();
  var month = days.getMonth() + 1;
  if (month < 10) {
    month = "0" + month;
  }
  var today = days.getDate();
  if (today < 10) {
    today = "0" + today;
  }
  if(type){
    return year + "-" + month + "-" + today;

  }
  return year + "/" + month + "/" + today;
}

/**
 *
 * @param {*} time 2019-11-12
 */
export function getCurrentWeek(time) {
  console.log(time);
  let week = new Date(time.replace(/\-/g, "/")).getDay();
  let arr = ['日', '一', '二', '三', '四', '五', '六'];
  return '星期' + arr[week];
}


/**
 * 两个时间相差的时间
 * @param {*} s1 时间戳大
 * @param {*} s2 时间戳小
 */
export function getRemainderTime(s1, s2) {
  let runTime = parseInt((s1 - s2) / 1000);
  let year = Math.floor(runTime / 86400 / 365);
  runTime = runTime % (86400 * 365);
  let month = Math.floor(runTime / 86400 / 30);
  runTime = runTime % (86400 * 30);
  let day = Math.floor(runTime / 86400);
  runTime = runTime % 86400;
  let hour = Math.floor(runTime / 3600);
  runTime = runTime % 3600;
  let minute = Math.floor(runTime / 60);
  runTime = runTime % 60;
  let second = runTime;
  return [year, month, day, hour, minute, second];
}


/**
 * 获得时间差,时间格式为 年-月-日 小时:分钟:秒 或者 年/月/日 小时：分钟：秒
 * 其中，年月日为全格式，例如 ： 2010-10-12 01:00:00
 * 返回精度为：秒，分，小时，天
 * @param  {String} startTime 开始时间
 * @param  {String} endTime   结束时间
 * @param  {String} diffType  差值单位
 * @return {Number}           差值
 */
export function getDateDiff(startTime, endTime, diffType) {
  //将xxxx-xx-xx的时间格式，转换为 xxxx/xx/xx的格式
  startTime = startTime.replace(/\-/g, "/");
  endTime = endTime.replace(/\-/g, "/");
  // console.log("getDateDiff", startTime, endTime);
  //将计算间隔类性字符转换为小写
  diffType = diffType.toLowerCase();
  var sTime = new Date(startTime); //开始时间
  var eTime = new Date(endTime); //结束时间
  //作为除数的数字
  var divNum = 1;
  switch (diffType) {
  case "second":
    divNum = 1000;
    break;
  case "minute":
    divNum = 1000 * 60;
    break;
  case "hour":
    divNum = 1000 * 3600;
    break;
  case "day":
    divNum = 1000 * 3600 * 24;
    break;
  default:
    break;
  }
  return parseInt((eTime.getTime() - sTime.getTime()) / parseInt(divNum));
};


/**
 * 如果传入的d为空，则内部会拿当前的date，返回2018-01-01
 * @param {date} d
 */
export function getShortDateWithBracket(d) {
  try {
    if (!d) d = new Date();
    var year = d.getFullYear();
    var month = '0' + (d.getMonth() + 1);
    month = month.slice(-2);
    var day = '0' + d.getDate();
    day = day.slice(-2);
    return year + '-' + month + '-' + day;
  } catch (err) {
    return '';
  }
}

export function getPreDate(timeStr, dayGap) {
  var date = new Date(timeStr + ' 00:00:00');
  var time1 = date.getTime() + (dayGap + 1) * (24 * 60 * 60 * 1000); //获取明天
  var date1 = new Date(time1);
  var Y = date1.getFullYear() + '-';
  var M = (date1.getMonth() + 1 < 10 ? '0' + (date1.getMonth() + 1) : date1.getMonth() + 1) + '-';
  var D = (date1.getDate() < 10 ? '0' + (date1.getDate()) : date1.getDate());
  var tmpStr = Y + M + D;
  return tmpStr;
}

export function getCurrentWeek2(time) {
  let week = new Date(time.replace(/\-/g, "/")).getDay();
  let arr = ['日', '一', '二', '三', '四', '五', '六'];
  return '周'+arr[week];
}

export function getCurrentWeek3(time) {
  let week = new Date(time.replace(/\-/g, "/")).getDay();
  let arr = ['日', '一', '二', '三', '四', '五', '六'];
  return arr[week];
}
